<?php

namespace App\Kuafu\Order\Model;

use App\Kuafu\Base\Model\BaseModel;
use App\Kuafu\Order\Enum\CodeEnum;

class ConsumerOrder extends BaseModel
{
    public $incrementing = false;

    protected $connection = 'mysqlOrderAll';
    protected $table      = 'consumer_order';
    protected $primaryKey = 'orderId';

    protected $fillable = [
        'orderId',
        'brandId',
        'shopId',
        'userId',
        'platformId',
        'images',
        'originalPrice',
        'payPrice',
        'discountPrice',
        'orderStatus',
        'shouldPrice',
        'orderShouldPrice',
        'count',
        'completeTime',
        'createdAt',
        'updatedAt',
        'createdByUid',
        'updatedByUid',
    ];

    protected $hidden = [];

    /**
     * 插入主表数据
     *
     * @param $data
     */
    public static function insertOrder($data)
    {
        self::query()->insert($data);
    }

    /**
     * 用户小程序列表数据
     *
     * @param $userId
     * @param $pageSize
     * @param $pageNum
     * @param $shopId
     * @param int $flagComplain
     * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator
     */
    public static function getUserAllOrderList(
        $userId,
        $userUnionid,
        $pageSize,
        $pageNum,
        $shopId,
        $flagComplain = CodeEnum::ORDER_STATUS_DEFAULT
    ) {
        $field = [
            'orderId',
            'shopId',
            'createdAt',
            'payPrice',
            'orderStatus',
            'shouldPrice',
            'payStatus',
            'orderShouldPrice',
            'count',
            'images',
            'originalPrice',
        ];
        return self::query()
                   ->when($userId > 0, function ($query) use ($userId) {
                       $query->where('userId', $userId);
                   })
                   ->when($userUnionid, function ($query) use ($userUnionid) {
                       $query->where('platformId', $userUnionid);
                   })
                   ->when(
                       $flagComplain == CodeEnum::ORDER_STATUS_APPLET,
                       function ($query) {//1-小程序投诉（获取支付完成的订单，最近10条）
                           $query->where('orderStatus', CodeEnum::ORDER_STATUS_FINISHED);
                       }
                   )
                   ->whereBetween('createdAt', [time() - 60 * 86400, time()]) // 最多查 2 个月之内的数据
                   ->orderBy('createdAt', 'DESC')
                   ->paginate($pageSize, $field, 'page', $pageNum);
    }
}